//
//  FilterComputerPlaysMisere.m
//  PrefCore
//
//  Created by Sergey on 6/5/14.
//  Copyright (c) 2014 Play-on-smart. All rights reserved.
//

#import "PSFilter.h"

PSHandHash PSFilterComputerPlaysMisere(PSHandHash candidates, PSTrickHash trick) {
    assert(candidates != 0); // There must be at least one candidate card
    if (trick == 0) {
        // first hand
        for (int i = 0 ; i != PS_CARD_SUIT_RISING_LEN ; i++) {
            PSCardSuit s = PSCardSuitRising[i];
            PSCardRankSet cards = PSHandGetSuit(candidates, s);
            if (cards == kMaskSeven || (cards & kMaskSevenOrEight) == kMaskSevenOrEight) {
                return PSHandWithOneCard([PSCard cardWithSuit:s andRank:kRankSeven]);
            }
        }
    } else {
        PSCard *c = PSTrickHighestCard(trick, kSuitNone);
        PSCardRankSet cards = PSHandGetSuit(candidates, c.suit);
        PSCardRank lower = PSCardSetNextLowerRank(cards, c.rank);
        if (lower != kRankNull) {
            return PSHandWithOneCard([PSCard cardWithSuit:c.suit andRank:lower]);
        }
        if (cards == 0) {
            for (int i = 0 ; i != PS_CARD_SUIT_RISING_LEN ; i++) {
                PSCardSuit s = PSCardSuitRising[i];
                PSCardRankSet cardsInSuit = PSHandGetSuit(candidates, s);
                if (cardsInSuit != 0) {
                    return PSHandWithOneCard([PSCard cardWithSuit:s andRank:PSCardSetHighestRank(cardsInSuit)]);
                }
            } // This line cannot be reached, because we know that the hand is not empty
        }
    }
    return candidates;
}
